package com.venta.autopartes.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

public class TransferFileFTP extends FTPClient {
	private String workPath;

	public TransferFileFTP(String server, String user, String password,
			int port, String workPath) {
		try {
			this.enterLocalPassiveMode();
			this.connect(server, port);
			this.login(user, password);
			if(workPath!=null && workPath.equalsIgnoreCase("")){
				this.changeWorkingDirectory(workPath);
			}
			System.out.println(this.getReplyString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean sendFile(File file) {
		boolean result = false;
		FileInputStream fis = null;

		try {

			// Create an InputStream of the file to be uploaded
			fis = new FileInputStream(file);

			// Store file to server
			//this.setFileType(fileType);
			System.out.println("Sending... " + file.getName() + " file");
        	result = this.storeFile(file.getName(), fis); 
			System.out.println("*** " + this.getStatus() + " ***");
			String[] replyStrings = this.getReplyStrings();
			for (String reply : replyStrings) {
				System.out.println(" ------  " + reply);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public boolean sendFile(List<File> fileList) {
		boolean result = true;
		for(File file:fileList){
			if(sendFile(file)==false){
				result=false;
			}
		}
		return result;
	}
	
	public void logoutAndDisconnect(){
		try{
			if (this.isConnected()){
				this.logout();
				this.disconnect();
			}	
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}

	public String getWorkPath() {
		return workPath;
	}

	public void setWorkPath(String workPath) {
		this.workPath = workPath;
	}
	
	

}
